﻿using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using NorthwindDataservice;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NorthwindWebservice.Controllers
{
    [Route("api/categories")]
    public class CategoriesController : Controller
    {
        DataService _dataService;

        public CategoriesController(DataService dataService)
        {
            _dataService = dataService;
        }

        [HttpGet]
        public IActionResult GetCategories()
        {
            var categories = _dataService.GetCategories();
            return Ok(categories);
        }

        [HttpGet("{id}")]
        public IActionResult GetCategory(int id)
        {
            var category = _dataService.GetCategory(id);

            if (category == null)
            {
                return NotFound();
            }

            return Ok(category);
        }

        // [FromBody] attribute tells .net to look in the body of the request instead of the URL
        // jObject will automatically parse the string in the request's body into a JSON object for further processing
        [HttpPost]
        public IActionResult CreateCategory([FromBody] JObject categoryData)
        {
            string name = categoryData.GetValue("Name").ToString();
            string description = categoryData.GetValue("Description").ToString();

            var category = _dataService.CreateCategory(name, description);
            string url = string.Format("{0}/api/categories/{1}", GetBaseUrl(), category.Id);
            return Created(url, category);
        }

        [HttpDelete("{id}")]
        public IActionResult DeleteCategory(int id)
        {
            bool success = _dataService.DeleteCategory(id);

            if (!success)
            {
                return NotFound();
            }

            return Ok();
        }

        [HttpPut("{id}")]
        public IActionResult UpdateCategory(int id, [FromBody] JObject categoryData)
        {
            string name = categoryData.GetValue("Name").ToString();
            string description = categoryData.GetValue("Description").ToString();
            if (_dataService.UpdateCategory(id, name, description))
            {
                return Ok();
            }
            else return NotFound();
            
        }

        private string GetBaseUrl()
        {
            return string.Format("{0}://{1}", Request.Scheme, Request.Host);
        }
    }
}